<template>
  <div class="oe-wrong-question">
    <div class="oe-question-title">
      <span class="oe-top-split"></span>
      <span class="oe-wrong-text"
        >错题统计
        <a-tooltip placement="bottomLeft">
          <template slot="title">只统计批阅完成的学生的试题数据</template>
          <span class="iconfont icon-wenti"></span>
        </a-tooltip>
      </span>
    </div>
    <div class="oe-wrong-search">
      <span class="oe-wrong-select">
        题目类型：
        <a-select
          mode="multiple"
          placeholder="请选择题型"
          style="min-width: 200px"
          v-model="searchQuesType"
          @change="handleChangeQuesType"
        >
          <a-select-option v-for="item in questionTypeList" :key="item.value" :value="item.value">
            {{ item.name }}
          </a-select-option>
        </a-select>
      </span>
      <span class="oe-wrong-select">
        选择试卷：
        <a-select v-model="searchExamStruct" style="width: 200px" @change="handleChange" placeholder="请选择试卷">
          <a-select-option :value="item" v-for="(item, index) in examStruct" :key="index"
            >试卷{{ item }}</a-select-option
          >
          <a-select-option :value="item" v-for="(item, index) in examRepairStruct" :key="index"
            >试卷{{ item }}</a-select-option
          >
        </a-select>
      </span>
      <span class="oe-wrong-change" @click="showErrorWindow">切换查看列表</span>
      <a-button type="primary" style="background-color:#86bde1" @click="getOneExamQuesStaticData()"
        >手动统计考试错题数据</a-button
      >
    </div>
    <div class="oe-wrong-echart">
      <v-chart ref="wrongEchart" @click="clickOneQuestionInfo" :options="wrongOption"></v-chart>
    </div>

    <!--  错题详情分析 -->
    <a-modal
      v-model="visibleQuestionData"
      title="错题详情分析"
      width="800px"
      wrapClassName="oe-modal__manage"
      :afterClose="displayCancel"
      :footer="null"
    >
      <div class="q-title" v-loading="loading">
        <a-button class="q-type" type="primary">{{ QuestionTypeConversion(questionInfo) }}</a-button>

        <span class="q-index">{{ questionIndex }}</span> /
        <span>{{ questionCount }}</span>
        <span class="q-score">（{{ questionInfo.Score }}分）</span>
      </div>
      <div class="q-content" v-html="questionInfo.Title"></div>

      <div calss="q-dataJSON" v-if="!showSubQuesDom">
        <a-radio-group @change="onChange" v-if="questionInfo.QuestionType != 7 && questionInfo.QuestionType != 4 && questionInfo.QuestionType != 5">
          <a-radio class="radioStyle" :value="1" v-for="item in DataJson" :key="item.SortOrder">
            <span>{{ letter[item.SortOrder] }}：</span>
            <span class="q-details" v-html="item.Content"></span>
          </a-radio>
        </a-radio-group>
        <div class="" v-if="questionInfo.QuestionType == 7">
          <div class="" v-for="item in JSON.parse(questionInfo.DataJson)" :key="item" style="margin-left: 20px;">
            <span>{{ letter[item.SortOrder] }}：</span>
            <span class="q-details" v-html="item.optionContent"></span>
          </div>
          选项：
          <div class="" v-for="item in JSON.parse(questionInfo.Answer)" :key="item" style="margin-left: 20px;">
            <span>{{ letter[item.SortOrder] }}：</span>
            <span class="q-details" v-html="item.optionAnswerContent"></span>
          </div>
        </div>
      </div>
      <div class="q-answer" v-if="!showSubQuesDom && questionInfo.QuestionType != 4 && questionInfo.QuestionType != 6">正确答案:{{ answerConversion(questionInfo) }}</div>
      <div class="q-answer" v-if="!showSubQuesDom && questionInfo.QuestionType == 4">
        <div class="q-answer-left">正确答案:</div>
        <div class="q-answer-right">
          <div v-for="(item,index) in answerConversion(questionInfo)" :key="index">
            <div class="q-answer-num">填空{{backQuesNum[index]}}:</div>
            <div class="q-answer-content">
              <div v-for="(answer,key) in item.answerList" :key="key">{{key+1}}、{{answer.Content}}</div>
            </div>
          </div>
        </div>
      </div>
      <div class="q-answer" v-if="!showSubQuesDom && questionInfo.QuestionType == 6">正确答案:<span v-html="answerConversion(questionInfo)"></span></div>
      <a-divider />
      <div class="answer-analysis">
        <div class="sub-ques-div" v-if="showSubQuesDom">
          <div class="sub-content" v-for="(it, it_index) in subQuesList" :key="it.QuestionId">
            <a-button class="sub-q-SortOrder" type="primary">{{ QuestionTypeConversion(it) }}</a-button>
            <span>10-{{ ++it_index }}</span
            >( <span class="q-score">{{ it.Score }}分</span>)
            <a-row>
              <a-col :span="24">
                <div v-html="it.Title"></div>
              </a-col>
              <a-col :span="8">
                <div class="sub-q-answer" v-if="it.QuestionType != 6">正确答案:{{ answerConversion(it) }}</div>
                <div class="sub-q-answer" v-else>正确答案: <span v-html="answerConversion(it)"></span> </div>
              </a-col>
              <a-col :span="8" :offset="8">
                <div v-for="(ti, index) in it.StuSelSubAnsNumArray" :key="index">
                  <div v-if="it.QuestionType != 3">
                    <div :class="`circle-icon-${index}`">选项 {{ ti }}</div>
                  </div>
                </div>
                <div v-if="it.QuestionType == 3">
                  <div class="circle-icon-0">正确 {{ it.SubRightAnswer }}</div>
                  <div class="circle-icon-1">错误 {{ it.SubWrongAnswer }}</div>
                </div>
              </a-col>
            </a-row>

            <a-row style=" background: rgba(238, 243, 246, 1); margin-top:6px">
              <a-col
                v-for="(item, i) in it.StuSelSubAnsNumArray"
                :key="i"
                class="sub-ques-answer"
                :class="classConversion(i)"
                :style="roteConversion(item, it.StuSelSubAnsNumArray)"
                :span="2"
              ></a-col>
              <a-col
                v-if="it.QuestionType == 3"
                class="sub-ques-answer ans-0"
                :style="ratejudge(it, 1)"
                :span="18"
              ></a-col>
              <a-col
                v-if="it.QuestionType == 3"
                class="sub-ques-answer ans-1"
                :style="ratejudge(it, -1)"
                :span="6"
              ></a-col>
            </a-row>
          </div>
        </div>
        <a-button class="q-line" type="primary"></a-button>
        <span class="q-any-line">数据分析</span>
        <div class="oe-question-echarts">
          <a-button
            class="q-next-pre q-next-pre-left"
            v-if="questionIndex != 1"
            type="primary"
            @click="switchQuestion(-1)"
            shape="circle"
            icon="left"
          ></a-button>
          <v-chart ref="questionErrorEchart" :options="questionErrorOptions"></v-chart>
          <a-button
            class="q-next-pre q-next-pre-right"
            v-if="questionIndex != questionCount"
            type="primary"
            @click="switchQuestion(1)"
            shape="circle"
            icon="right"
          ></a-button>
        </div>
        
      </div>
    </a-modal>
  </div>
</template>

<script>
export default {
  name: 'wrongAnalysis',
  data() {
    return {
      questionCount: 1,
      loading: false,
      letter: ['A', 'B', 'C', 'D', 'E', 'F', 'G'],
      backQuesNum: ['一', '二', '三', '四', '五', '六', '七', '八', '九', '十', '十一', '十二', '十三'],
      q_type: [
        '',
        '单选题',
        '多选题',
        '判断',
        '客观填空题',
        '主观填空题',
        '问答题',
        '匹配题',
        '阅读理解',
        '完形填空',
        '文件作答题',
        '视听题',
        '主观阅读理解',
        '主观完形填空'
      ],
      subQuesList: [],
      showSubQuesDom: false,
      questionIndex: 1,
      questionInfo: {},
      DataJson: {},

      searchQuesType: [] /*  */,
      searchExamStruct: undefined,
      visibleQuestionData: false,

      questionErrorOptionsList: [],
      questionErrorSelCount: 0,
      // 分页配置
      modalPagination: {
        pageSizeOptions: ['10', '20', '50', '100', '1000'],
        showSizeChanger: true,
        showTotal(total) {
          return `共 ${total} 条`;
        },
        onShowSizeChange: (current, pageSize) => {
          this.modalPagination.current = current;
          this.modalPagination.pageSize = pageSize;
        },
        onChange: (current, pageSize) => {
          this.modalPagination.current = current;
          this.modalPagination.pageSize = pageSize;
        },
        buildOptionText(props) {
          return props.value + '条/页';
        },
        current: 1,
        pageSize: 10,
        total: 0
      },
      // 各题型
      questionErrorOptions: {
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          icon: 'circle',
          orient: 'horizontal',
          bottom: 10,
          itemGap: 10,
          itemHeight: 15,
          itemWidth: 15,
          formatter: (val) => {
            let index = this.questionErrorOptionsList.findIndex((item) => {
              return item.name === val;
            });
            if (index > -1) {
              let rate = (
                (this.questionErrorOptionsList[index].value * 100) /
                (this.questionErrorSelCount > 0 ? this.questionErrorSelCount : 1)
              ).toFixed(2);

              return `${val}：${rate}%`;
            } else {
              return val;
            }
          }
        },
        color: ['#F9CD33', '#FFA800', '#F86846', '#78C446', '#5ED8A9', '#4FC5EA', '#8F55E7', '#605AD8', '#3C43FF'],
        series: [
          {
            name: '',
            type: 'pie',
            center: ['60%', '50%'],
            radius: ['45%', '65%'],
            avoidLabelOverlap: false,
            label: {
              show: false,
              position: 'center'
            },
            labelLine: {
              show: false
            },
            data: []
          }
        ]
      },
      // 错题
      wrongOption: {
        legend: {
          itemGap: 20,
          top: '7%',
          icon: 'circle'
        },
        dataZoom: {
          type: 'slider',
          show: true,
          xAxisIndex: [0],
          start: 0,
          end: 50,
          bottom: '3%'
        },
        tooltip: {},
        color: ['#FF74F7', '#78AEF9', '#e3647b'],
        grid: {
          left: '3%',
          right: '6%',
          bottom: '15%',
          top: '20%',
          containLabel: true
        },
        dataset: {
          dimensions: ['题干', '错题率(%)', '未作答学生数', '未批学生数'],
          source: []
        },
        xAxis: {
          type: 'category',
          name: '题目',
          axisLabel: {
            interval: 0,
            formatter: function(value) {
              return value.split('').length > 10 ? value.substring(0, 10) + '...' : value;
            }
          }
        },
        yAxis: {
          type: 'value',
          minInterval: 1
        },
        series: [
          {
            type: 'bar',
            barWidth: '18%',
            itemStyle: {
              normal: {
                barBorderRadius: 50
              }
            }
          },
          {
            type: 'bar',
            barWidth: '18%',
            itemStyle: {
              normal: {
                barBorderRadius: 50
              }
            }
          },
          {
            type: 'bar',
            barWidth: '18%',
            itemStyle: {
              normal: {
                barBorderRadius: 50
              }
            }
          }
        ]
      },
      //错题统计
      questionTypeList: [  
        { value: 1, name: '单选题(客观)' },      
        { value: 2, name: '多选题(客观)' },        
        { value: 3, name: '判断题(客观)' },
        { value: 4, name: '填空题(客观)' },
        { value: 5, name: '填空题(主观)' },
        { value: 6, name: '问答题(主观)' },
        { value: 7, name: '匹配题(主观)' },
        { value: 8, name: '阅读理解(客观)' },
        { value: 12, name: '阅读理解(主观)' },
        { value: 9, name: '完形填空(客观)' },
        { value: 13, name: '完形填空(主观)' },
        { value: 11, name: '视听题(客观)' }
      ]
    };
  },
  props: {
    examid: {
      type: String,
      default: ''
    },
    examStruct: [],
    examRepairStruct: []
  },
  methods: {
    roteConversion(i, d) {
      var count = 0;
      d.forEach((item) => {
        count += item;
      });

      return 'width:' + (i / count) * 100 + '%';
    },
    classConversion(val) {
      return 'ans-' + val;
    },
    answerConversion(val) {
      var that = this,
        letter2 = ['错误', '正确'],
        key = '未作答';

      switch (Number(val.QuestionType)) {
        case 1:
          key = that.letter[Number(val.Answer)];
          break;
        case 2:
          var an_a = val.Answer.split(','),
            lett = [];
          an_a.forEach((item) => {
            lett.push(that.letter[item]);
          });

          key = lett.join(',');
          break;
        case 3:
          key = letter2[Number(val.Answer)];
          break;
        case 4:
          var arr = [];
          var maxNum = 0;
          for (let i = 0; i < val.AnswerList.length; i++) {
              if (maxNum < val.AnswerList[i].SortOrder) {
                maxNum = val.AnswerList[i].SortOrder
              }            
          };
          for (let i = 0; i < maxNum+1; i++) {
            let lis = {
              num: i,
              answerList: []
            };
            arr.push(lis);
          };
          for (let i = 0; i < arr.length; i++) {
            for (let keys = 0; keys < val.AnswerList.length; keys++) {
              if (arr[i].num == val.AnswerList[keys].SortOrder) {
                arr[i].answerList.push(val.AnswerList[keys]);
              }
            }
          };
          key = arr;
          break;
        case 5:
          key = val.Answer;
          break;
        case 6:
          key = val.Answer;
          break;
        case 7:
          key = '';
          for (let i = 0; i < val.AnswerList.length; i++) {
            if (i == val.AnswerList.length-1) {
              key = key + this.letter[val.AnswerList[i].OptionSelectContent]
            } else {
              key = key + this.letter[val.AnswerList[i].OptionSelectContent] +'、'
            }
          };
          break;
        default:
          key = '--';
          break;
      }
      return key;
    },
    QuestionTypeConversion(val) {
      return val.QuestionType ? this.q_type[val.QuestionType] : '';
    },
    switchQuestion(val) {
      this.questionIndex += val;

      var data = this.wrongQuesStatisList[this.questionIndex - 1];

      this.getOneQuestionInfo(data[4]);
    },
    //错题统计选择试卷
    handleChange(val) {
      this.searchExamStruct = val;
      this.getStuAnsErrorList(val);
    },
    //选择题型
    handleChangeQuesType(val) {
      this.searchQuesType = val;
      this.getStuAnsErrorList();
    }, //题目统计选择试卷
    //错题统计
    getStuAnsErrorList(r) {
      this.loading = true;
      var examStruct = r ? r : this.searchExamStruct;
      var that = this;
      this.searchExamStruct = examStruct;
      this.$http
        .post('/api/examStatistics/ExamAnaly/getPaperErrorQuesStaticList', {
          examId: this.examid,
          questionType: this.searchQuesType,
          examStruct: examStruct,
          isPaging: false
        })
        .then((res) => {
          this.loading = false;
          if (res.code > 0) {
            this.wrongQuesStatisList = [];
            // res.list.forEach((item) => {
            //   that.wrongQuesStatisList.push([item.QuestionTitle, item.WrongAnswerPer, item.NothingAnswerNum, item.examStuNoMarkedCount, item.QuestionId,item.Index]);
            // });
            res.list.forEach((item) => {
              that.wrongQuesStatisList.push([
                item.QuestionTitle,
                item.WrongAnswerPer,
                item.NothingAnswerNum,
                item.NoMarkedStuCount,
                item.QuestionId,
                item.Index
              ]);
            });

            that.questionCount = that.wrongQuesStatisList.length;

            this.wrongOption.dataset.source = this.wrongQuesStatisList;
            if (this.wrongOption.dataset.source.length < 20) {
              this.wrongOption.dataZoom.end = 100;
            } else if (this.wrongOption.dataset.source.length < 50) {
              this.wrongOption.dataZoom.end = 50;
            } else if (this.wrongOption.dataset.source.length < 101) {
              this.wrongOption.dataZoom.end = 25;
            } else if (this.wrongOption.dataset.source.length > 100) {
              this.wrongOption.dataZoom.end = 20;
            }
          } else {
            this.$message.warning(res.msg);
          }
        });
    },
    showErrorWindow() {
      if (this.searchExamStruct == null) {
        this.$message.warning('请先选择试卷');
      } else {
        this.$router.push({
          name: 'wrongStuList',
          params: {
            examid: this.examid,
            searchExamStruct: this.searchExamStruct
          }
        });
      }
    },
    //手动统计
    getOneExamQuesStaticData() {
      this.$http
        .post('/api/examStatistics/examanaly/getOneExamQuesStaticData', {
          workExamId: this.examid
        })
        .then((res) => {
          this.loading = false;
          if (res.code > 0) {
            if (this.searchExamStruct != null) {
              this.getStuAnsErrorList(this.searchExamStruct);
            }
            this.$message.success(res.msg);
          } else {
            this.$message.warning(res.msg);
          }
        });
    },
    clickOneQuestionInfo(val) {
      var id = val.data[4];
      this.questionIndex = val.data[5];
      this.getOneQuestionInfo(id);
    },
    //获取试卷单个题目作答统计
    getOneQuestionInfo(questionId) {
      var that = this;
      this.loading = true;
      this.$http
        .post('/api/examStatistics/examanaly/getOneQuestionInfo', {
          examId: this.examid,
          examStruct: this.searchExamStruct,
          questionId: questionId
        })
        .then((res) => {
          this.loading = false;
          if (res.code > 0) {
            this.visibleQuestionData = true;
            this.showSubQuesDom = false;
            this.questionInfo = res.questionInfo;
            this.DataJson = JSON.parse(res.questionInfo.DataJson);

            switch (res.questionInfo.QuestionType) {
              case 1:
              case 2:
                this.radioMultiSelect(res);
                break;
              case 3:
              case 4:
              case 5:
              case 6:
                this.judgeSel(res);
                break;
              case 7:
                this.judgeSel(res);
                this.matchingQues(res);
                break;
              case 8:
              case 9:
              case 11:
              case 12:
              case 13:
                this.showSubQuesDom = true;
                this.judgeSel(res);
                this.showSubQues(res);
                break;
              default:
                break;
            }
          } else {
            this.$message.warning(res.msg);
          }
        });
    },
    radioMultiSelect(res) {
      var that = this;
      this.questionErrorSelCount = 0;
      this.questionErrorOptionsList = [];
      res.stuSelAnsNumArray.forEach((v, i) => {
        that.questionErrorOptionsList.push({
          value: v,
          name: '选项' + that.letter[i]
        });
        that.questionErrorSelCount += v;
      });
      this.questionErrorOptions.series[0].data = this.questionErrorOptionsList;
    },
    judgeSel(res) {
      var that = this;
      this.questionErrorSelCount = 0;
      console.log(res);
      that.questionErrorOptionsList = [
        {
          value: res.stuAnswerInfo[0],
          name: '正确个数'
        },
        {
          value: res.stuAnswerInfo[1],
          name: '错误个数'
        },
        {
          value: res.stuAnswerInfo[2],
          name: '半对半错个数'
        }
      ];
      res.stuAnswerInfo.forEach((item) => {
        that.questionErrorSelCount += item;
      });

      this.questionErrorOptions.series[0].data = this.questionErrorOptionsList;
    },
    ratejudge(r, i) {
      var that = this;
      var rate = 0;
      let count = r.SubRightAnswer + r.SubWrongAnswer;
      if (i > 0) {
        rate = (r.SubRightAnswer / count) * 100;
      } else {
        rate = (r.SubWrongAnswer / count) * 100;
      }
      return 'width:' + rate + '%';
    },
    matchingQues(res) {
      var that = this;
    },
    showSubQues(res) {
      var that = this;
      this.subQuesList = res.subQuesList;
    }
  }
};
</script>
